import sqlite3
import os

class client_states:
    def __init__(self):
        self.states = {} # 格式：{client_id: [alert_state, sycdata_state]}

    def addNew(self, id):
        self.states[id] = [False, False]

    def getStates(self, id):
        return self.states[id]
    
    def response(self, id):
        self.states[id][0] = False
        self.states[id][1] = False
    
    def sendAll(self):
        for item in self.states.keys():
            self.states[item][1] = True


# 连接数据库并返回
def open_database():
    conn = sqlite3.connect('wellword.db')
    cursor = conn.cursor()
    return (conn, cursor)

# 关闭数据库
def close_database(db):
    db[0].close()

# 初始化数据库
def init_db():
    sql1 = '''
    CREATE TABLE UserInfo (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    picid INTEGER DEFAULT 0,
    gamestatus INTEGER CHECK(gamestatus IN (0,1))
    );'''
    sql2 = '''
    create table GameSteps(
    id integer primary key autoincrement,
    userid integer not null,
    chessstatus integer check(chessstatus in (1, 2)),
    boardblock integer check(boardblock between 0 and 8)
    );
    '''
    if not os.path.isfile('./wellword.db'):
        print('create database ...')
        db = open_database()
        db[1].execute(sql1)
        db[1].execute(sql2)
        db[0].commit()
        db[0].close()

# 查询图库数量
def get_pic_count():
    files = os.listdir('./static/images')
    return len(files)